package com.arpa.ntocc.common.common.validator.aspect;

import cn.hutool.core.util.StrUtil;
import com.arpa.ntocc.common.common.validator.annotation.PartyGroupNameExistConstraint;
import com.arpa.ntocc.common.domain.entity.PartyGroup;
import com.arpa.ntocc.common.mapper.PartyGroupMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 组织名称校验注解实现
 * @author liuxr
 * @date 2021年11月12日 15:33
 */
@Component
public class PartyGroupNameExistValidator implements ConstraintValidator<PartyGroupNameExistConstraint, Object> {

    @Resource
    private PartyGroupMapper partyGroupMapper;


    /**
     * 新增时校验整个平台组织信息
     * 编辑时排除当前组织信息
     * @param o       object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Object o, ConstraintValidatorContext context) {
        PartyGroup partyGroup = (PartyGroup) o;
        int count = 1;
        if (StrUtil.isNotBlank(partyGroup.getCode())) {
            //更新
            count = partyGroupMapper.selectCount(Wrappers.lambdaQuery(PartyGroup.class)
                    .eq(PartyGroup::getGroupName, partyGroup.getGroupName())
                    .ne(PartyGroup::getCode, partyGroup.getCode()));
        } else {
            //新增
            count = partyGroupMapper.selectCount(Wrappers.lambdaQuery(PartyGroup.class)
                    .eq(PartyGroup::getGroupName, partyGroup.getGroupName()));
        }
        return count <= 0;
    }
}
